package org.shopen.puremvc.view
{
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	import org.shopen.puremvc.ApplicationConstants;
	import org.shopen.puremvc.view.components.info.AboutWindow;

	public class AboutWindowMediator extends Mediator
	{
		public static const NAME : String = "AboutWindowMediator";
		
		protected var aboutWindow : AboutWindow = null;
		
		public function AboutWindowMediator(viewComponent:Object=null)
		{
			super(AboutWindowMediator.NAME, viewComponent);
		}
		
		override public function getMediatorName():String
		{
			return AboutWindowMediator.NAME;
		}
		
		protected function get application() : ShoPaint
		{
			return viewComponent as ShoPaint;
		}
		
		override public function listNotificationInterests():Array
		{
			return [ApplicationConstants.SHOW_ABOUT];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch(notification.getName())
			{
				case ApplicationConstants.SHOW_ABOUT:
					showAboutWindow();
					break;
			}
		}
		
		private function showAboutWindow() : void
		{
			// Make sure only one about window is shown
			if (aboutWindow == null)
			{
				aboutWindow = createWindow();
				PopUpManager.addPopUp(aboutWindow, application, true);
			}
			
			PopUpManager.bringToFront(aboutWindow);
			PopUpManager.centerPopUp(aboutWindow);
		}
		
		private function createWindow() : AboutWindow
		{
			var window : AboutWindow = new AboutWindow();
						
			window.addEventListener(CloseEvent.CLOSE, windowCloseListener);
			
			return window;
		}
		
		private function windowCloseListener(event : CloseEvent) : void
		{
			if (aboutWindow == event.target)
			{
				aboutWindow.removeEventListener(CloseEvent.CLOSE, windowCloseListener);
				PopUpManager.removePopUp(aboutWindow);
				aboutWindow = null;
			}
			else
			{
				sendNotification(ApplicationConstants.GENERAL_ERROR);
			}
		}
		
		protected function removeAboutWindow() : void
		{
			if (aboutWindow != null)
			{
				if (aboutWindow.hasEventListener(CloseEvent.CLOSE))
				{
					aboutWindow.removeEventListener(CloseEvent.CLOSE, windowCloseListener);
				}
				PopUpManager.removePopUp(aboutWindow);
				aboutWindow = null;
			}
		}
	}
}